import logging
import re

from QQLoginTool.QQtool import OAuthQQ
from django.contrib.auth import login
from django.http import JsonResponse, HttpResponseForbidden
from django.shortcuts import render, redirect
from django.conf import settings
from django.urls import reverse
from django.views import View
# Create your views here.
from django_redis import get_redis_connection

from carts.utils import merge_cart_cookies_to_redis
from meiduo_mall.utils.response_code import RETCODE
from oauth.models import OAuthQQUser
from oauth.utils import generate_access_token, check_access_token
from users.models import User

logger = logging.getLogger('django')

class QQAuthUserView(View):
    """用户扫码登录回调处理"""


    def get(self,request):
        """Oauth2.0认证"""
        code = request.GET.get('code')
        if not code:
            return HttpResponseForbidden('缺少ｃｏｄｅ')
        next = request.GET.get('state')

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI,state=next)

        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(e)
            return HttpResponseForbidden('Oauth2.0认证失败')
        # 检查用户是否绑定
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 没绑定
            access_token = generate_access_token(openid)
            content = {'access_token_openid':access_token}
            return render(request,'oauth_callback.html',content)
        else:
            qq_user = oauth_user.user
            # 状态保持
            login(request,qq_user)

            response = redirect(next)
            response.set_cookie('username',qq_user.username,max_age=3600*24*15)
            response = merge_cart_cookies_to_redis(request,qq_user,response)
            return response

    def post(self,request):
        """绑定ＱＱ用户"""
        mobile = request.POST.get('mobile')
        password= request.POST.get('password')
        access_token_openid = request.POST.get('access_token_openid')
        sms_code_client = request.POST.get('sms_code')
        next = request.GET.get('state')

        if not all([mobile,password,access_token_openid]):
            return HttpResponseForbidden('缺少参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseForbidden('请输入正确的手机号码')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden('请输入8-12位密码')
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile).decode()
        if sms_code_server is None:
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '验证码已过期'})
        if sms_code_server != sms_code_client:
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '验证码输入有误'})
        openid = check_access_token(access_token_openid)
        if not openid:
            return render(request, 'oauth_callback.html', {'openid_errmsg': 'xxxxxxx'})
        # 绑定用户
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 没有用户则创建
            user = User.objects.create_user(username=mobile,password=password,mobile=mobile)
        else:
            # 检查密码
            if not user.check_password(password):
                return render(request, 'oauth_callback.html', {'account_errmsg': '用户名或密码错误'})
        try:
            OAuthQQUser.objects.create(user=user,openid=openid)
        except:
            return render(request, 'oauth_callback.html', {'qq_login_errmsg': 'QQ登录失败'})

        # 保持状态，重定向
        login(request,user)
        response = redirect(next)


        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return response



class QQAuthURLView(View):
    """提供ＱＱ登录页面"""

    def get(self,request):
        """处理ｑｑ登录请求页面"""
        # ｎｅｘｔ表示从那个页面来的
        next = request.GET.get('next')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI,state=next)
        login_url = oauth.get_qq_url()

        return JsonResponse({'code':RETCODE.OK,'errmsg':'ok','login_url':login_url})

